package org.smoke.service;

import org.smoke.bean.User;
import org.smoke.bean.UserToken;
import org.smoke.dao.UserDAO;
import org.smoke.util.CipherUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;

/**
 * @author hezhiyu on 15/5/2.
 */
@Service
public class UserService {


    public static final String COOKIE_SPLIT = ";";

    public static final String AES_KEY = "EXChange";

    public static final String ENCODING = "UTF-8";

    @Autowired
    private UserDAO userDAO;

    public boolean checkUserExist(String name) {
        Long uid = userDAO.getUidByName(name);
        return uid != null && uid > 0;
    }

    public User registerUser(String name, String pass) {
        User user = new User();
        user.setName(name);
        user.setPassword(pass);
        user.setCreateTime(new Timestamp(System.currentTimeMillis()));
        Long uid = userDAO.saveUser(user);
        user.setUid(uid != null && uid > 0 ? uid: -1);
        return user;
    }

    public Long login(String name, String pass) {
        User user = userDAO.getUser(name, pass);
        return user != null ? user.getUid() : -1;
    }

    public String buildUserToken(Long uid, String ip) {
        long createTime = System.currentTimeMillis();
        String all = ip + COOKIE_SPLIT + uid.toString() + COOKIE_SPLIT + createTime;
        try {
            return CipherUtil.encByAES(all, AES_KEY);
        } catch (Exception e) {
//            LOG.info("Token Error");
            return null;
        }
    }

    public UserToken getUserToken(String cookie) {
        try {
            String decByAES = CipherUtil.decByAES(cookie, AES_KEY);
            String[] ss = decByAES.split(COOKIE_SPLIT);
            long uid = Long.parseLong(ss[1]);
            String ip = ss[0];
            long createTime = Long.parseLong(ss[2]);
            return new UserToken(ip, uid, createTime);
        } catch (Exception e) {
            return null;
        }
    }

}
